package wa.tools;

import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wa.jdk14logging.LogFormatter;

public class WaCliImpl {

	Logger log = LoggerFactory.getLogger(WaCliImpl.class);
	CommandLineParser parser = new PosixParser();
	CommandLine line;
	Options options;
	HelpFormatter formatter;
	long timer;
	
	@SuppressWarnings("static-access")
	public WaCliImpl(){
		options = new Options();
		Option help = new Option( "help", "print this message." );
		Option version = new Option( "version", "print the version information and exit." );
		options.addOption(help);
		options.addOption(version);
		options.addOption(OptionBuilder.withLongOpt("jdbc-url")
								       .withDescription("use URL for connection")
								       .hasArg()
								       .withArgName("URL")
								       .create("U"));

		options.addOption(OptionBuilder.withLongOpt("add-tosecfile")
			       .withDescription("add given file to database")
			       .hasArgs()
			       .withArgName("FILE")
			       .withArgName("FILEB")
			       .create("a"));
		
		options.addOption(OptionBuilder.withLongOpt("import-directory")
			       .withDescription("import recursively all tosec files in given DIR")
			       .hasArg()
			       .withArgName("DIR")
			       .create("i"));
	
		
		
				
		formatter = new HelpFormatter();
		
	}
	
	// public void init(String[] args, Settings, PU)
	public void init(String[] args) {
		try {
			line = parser.parse(options,args);
			
			timer= System.currentTimeMillis();
			
			
			java.util.logging.Logger jdk4log = java.util.logging.Logger.getLogger("");
			Handler[] handlers = jdk4log.getHandlers();
			for (Handler hand : handlers) {
				if (hand instanceof ConsoleHandler) {
					ConsoleHandler cHand = (ConsoleHandler) hand;
					LogFormatter fmt = new LogFormatter();
					
					fmt.setFlatMode(true);
					cHand.setFormatter(fmt);
				}
			}
			
		} catch (ParseException e) {
			log.error("oops", e);
			log.info("try -help");
		}
	}
	
	public void process () {
		log.info("processing..");
		if (line.hasOption("help")) {
			HelpFormatter formatter = new HelpFormatter(); 
			formatter.printHelp("wa", options, true);
		} else if (line.hasOption("version")){
			log.info("version is ..");
		} else if (line.hasOption("a")) {
			log.info("adding:"+line.getOptionValue("a"));
		}
		
		
	}
	
	public void destroy () {
		
	}
}
